package com.zz.hhbl.ui

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.TextUtils
import androidx.activity.OnBackPressedCallback
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.amap.api.location.AMapLocationClient
import com.amap.api.location.CoordinateConverter
import com.amap.api.location.DPoint
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.zz.framework.core.base.BaseActivity
import com.zz.framework.core.event.RecordSosInfoEvent
import com.zz.framework.core.event.ShowLockSceenEvent
import com.zz.framework.core.event.ShowSafeTipEvent
import com.zz.framework.core.ext.clickN
import com.zz.framework.core.ext.getAppVersion
import com.zz.framework.core.ext.gone
import com.zz.framework.core.ext.loadUrl
import com.zz.framework.core.ext.onClick
import com.zz.framework.core.ext.toLanguage
import com.zz.framework.core.ext.viewBinding
import com.zz.framework.core.ext.visible
import com.zz.framework.core.toast.ToastUtils
import com.zz.framework.core.utils.ActivityStackManager
import com.zz.framework.core.utils.AudioPlayerUtils
import com.zz.framework.core.utils.DeviceUtils
import com.zz.framework.core.utils.LogUtils
import com.zz.framework.core.utils.MediaPlayerUtils
import com.zz.framework.core.utils.VersionUtils
import com.zz.framework.core.utils.language.LanguageManager
import com.zz.framework.core.utils.language.Strings
import com.zz.framework.core.xdialog.XDialog
import com.zz.hhbl.config.GlobalCache
import com.zz.hhbl.databinding.ActivityLaunchBinding
import com.zz.hhbl.entity.VersionType
import com.zz.hhbl.event.OnLanguageSwitchEvent
import com.zz.hhbl.event.VersionUpdateEvent
import com.zz.hhbl.ui.earphone.EarphoneChoiceFragment
import com.zz.hhbl.utils.GeofenceUtils
import com.zz.hhbl.utils.LocalUrlUtils
import com.zz.hhbl.utils.LocationAlarmManager
import com.zz.hhbl.utils.location.LocationViewModel
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.locationtech.jts.geom.Coordinate

/**
 * Copyright © 2025 zhun All rights reserved.
 * Created by ZhaoZhun on 2025/2/18 14:46.
 * @author: ZhaoZhun 1820022519@qq.com
 * @version: V1.0
 */
@AndroidEntryPoint
class LaunchActivity : BaseActivity() {
    private val viewModel: CommonViewModel by viewModels()
    private val locationViewModel: LocationViewModel by viewModels()
    private val binding: ActivityLaunchBinding by viewBinding()
    private var downloadPath: String = LocalUrlUtils.getLocalFolderPath()
    private val handler = Handler(Looper.getMainLooper())
    var insideCircleFenceCount = 0
    var insidePolygonFenceCount = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        AMapLocationClient.updatePrivacyShow(this, true, true)
        AMapLocationClient.updatePrivacyAgree(this, true)
        setOnApplyWindowInsetsPadding(binding.root)
        LogUtils.error("downloadPath:$downloadPath")
        binding.tvVersion.text = "Version ${getAppVersion()}"
        onBackPressedDispatcher.addCallback(object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
            }
        })
        requestPermission()
        viewModel.loginState.observe(this) {
            dismissProgress()
            if (GlobalCache.isFirstLaunch()) {
                showProgress()
                viewModel.getAllData()
            }
            showProgress()
            viewModel.getVersion()
        }
        viewModel.fetchMultipleRequestsState.observe(this) {
            dismissProgress()
        }
        showBackgroundImage()
        binding.viewToSetting.clickN(10) {
            DeviceUtils.openSettings(this@LaunchActivity)
        }
        if (getIntent().getBooleanExtra("isBack", false)) {
            binding.btnBack.text = Strings.返回.toLanguage()
            binding.btnBack.visible()
            binding.btnBack.onClick {
                finish()
            }
        }
        LocationAlarmManager.startUpdateAlarm()
    }

    override fun initView(savedInstanceState: Bundle?) {
        binding.btnChinese.setText(Strings.中文)
        binding.btnEnglish.setText(Strings.英文)
        binding.btnChinese.onClick {
            binding.btnChinese.setText(Strings.中文)
            binding.btnEnglish.setText(Strings.英文)
            LanguageManager.currentLangCode = "zh-CN"
            LanguageManager.currentLangValue = Strings.中文
            onLanguageChange()
        }
        binding.btnEnglish.onClick {
            binding.btnChinese.setText(Strings.中文)
            binding.btnEnglish.setText(Strings.英文)
            LanguageManager.currentLangCode = "en"
            LanguageManager.currentLangValue = Strings.English
            onLanguageChange()
        }
    }


    fun onLanguageChange() {
        LanguageManager.resetLanguageMap()
        EventBus.getDefault().post(OnLanguageSwitchEvent())
        if (getIntent().getBooleanExtra("isBack", false)) {
            finish()
        } else {
            startParentActivity(EarphoneChoiceFragment::class.java)
        }
    }

    override fun onStop() {
        super.onStop()
        AudioPlayerUtils.newInstance().stop()
    }

    // 3s一次
    private fun startLocationTimer(interval: Long = 3000) {
        handler.postDelayed(object : Runnable {
            override fun run() {
                handler.postDelayed(this, interval)
                requestLocation()
            }
        }, 0)
    }

    private fun stopLocationTimer() {
        handler.removeCallbacksAndMessages(null)
    }

    var updateDialog: XDialog? = null
    override fun initObserver() {
        viewModel.allCacheMapState.observe(this) {
            dismissProgress()
            GlobalCache.setIsFirstLaunch(false)
            it?.forEach { language, entity ->
                run {
                    //讲解音频
                    entity.tourGuideCommentary?.map { it.lectureAudio.orEmpty() }?.filter { it.isNullOrEmpty().not() }?.let {
                        download(it)
                    }
                    //获取景点欢迎页面
                    entity.spotInfo?.let {
                        it.welcomeData?.firstOrNull()?.url?.let {
                            binding.ivBackground.loadUrl(it)
                        }
                        it.bootPageData?.filter { it.type?.contains("video") == true }?.map { it.url.orEmpty() }?.let { urls ->
                            download(urls)
                        }
                    }
                }
            }
            binding.groupCache.gone()
            binding.groupLanguage.visible()
            showBackgroundImage()
        }
        viewModel.downloadApkFailureLiveData.observe(this) {
            dismissProgress()
            ToastUtils.show(Strings.下载失败)
        }
        viewModel.downloadApkSuccessLiveData.observe(this) {
            ToastUtils.show(Strings.升级中.toLanguage())
            DeviceUtils.installApkSlient(it)
        }
        viewModel.versionState.observe(this) {
            dismissProgress()
            it?.forEach {
                when (it.type) {
                    //app版本
                    VersionType.APP.type -> {
                        if (VersionUtils.versionShouldUpdate(it.version, getAppVersion())) {
                            it.url?.let {
                                viewModel.downloadApk(it)
                            }
                        }
                    }
                    //景点信息
                    VersionType.SPOT.type -> {
//                        if (VersionUtils.versionShouldUpdate(it.version, GlobalCache.getSpotVersion())) {
                        showProgress()
                        viewModel.getSpotInfo()
//                        }
                    }

                    VersionType.TOUR_GUIDE_COMMENTARY.type -> {
//                        if (VersionUtils.versionShouldUpdate(it.version, GlobalCache.getTourGuideCommentaryVersion())) {
                        showProgress()
                        viewModel.getTourGuideCommentary()
//                        }
                    }

                    VersionType.DIGITAL_HUMAN.type -> {
//                        if (VersionUtils.versionShouldUpdate(it.version, GlobalCache.getDigitalHumanVersion())) {
                        showProgress()
                        viewModel.digitalHuman()
//                        }
                    }

                    VersionType.ELECTRONIC_FENCE.type -> {
//                        if (VersionUtils.versionShouldUpdate(it.version, GlobalCache.getElectronicFenceVersion())) {
                        showProgress()
                        viewModel.fence()
//                        }
                    }
                }
            }
        }
        viewModel.spotInfoState.observe(this) {
            dismissProgress()
            it?.let {
                it.welcomeData?.firstOrNull()?.url?.let {
                    binding.ivBackground.loadUrl(it)
                }
                it.bootPageData?.filter { it.type?.contains("video") == true }?.map { it.url.orEmpty() }?.let { urls ->
                    download(urls)
                }
                GlobalCache.setSpotInfo(it)
            }
            showBackgroundImage()
        }
        viewModel.tourGuideCommentaryState.observe(this) {
            dismissProgress()
            it?.let {
                GlobalCache.setTourGuideCommentary(it)
                it.filter { it.lectureAudio.isNullOrEmpty().not() }.map { it.lectureAudio.orEmpty() }.let {
                    download(it)
                }
            }
        }
        viewModel.fenceState.observe(this) {
            dismissProgress()
        }
        viewModel.digitalHumanState.observe(this) {
            dismissProgress()
            it?.let {
                GlobalCache.setDigitalHuman(it)
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        stopLocationTimer()
        MediaPlayerUtils.getInstance().stop()
    }

    private fun showBackgroundImage() {
        GlobalCache.getSpotInfo()?.welcomeData?.firstOrNull()?.let {
            binding.ivBackground.loadUrl(it.url)
            binding.groupLanguage.visible()
        }
    }

    private fun download(urls: List<String>) {
        viewModel.download(urls)
    }

    fun handleProgress(isShowProgress: Boolean = true) {
        if (isShowProgress.not()) {
            binding.groupCache.gone()
            binding.groupLanguage.visible()
        } else {
            binding.groupCache.visible()
            binding.groupLanguage.gone()
        }
    }


    private fun requestPermission() {
        XXPermissions.with(this)
            .permission(
                Permission.CAMERA,
                Permission.RECORD_AUDIO,
                Permission.GET_INSTALLED_APPS,
                Permission.MANAGE_EXTERNAL_STORAGE,
                Permission.ACCESS_FINE_LOCATION,
            )
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    if (!allGranted) {
                        ToastUtils.show(Strings.获取部分权限成功但部分权限未正常授予.toLanguage())
                        return
                    }
                    handleProgress(false)
                    viewModel.initKetch()
                    showProgress()
                    viewModel.login()
                    if(GlobalCache.getFence().filter { TextUtils.equals(it.status, "1") }.isNullOrEmpty().not()) {
                        startLocationTimer()
                    }
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {
                    if (doNotAskAgain) {
                        ToastUtils.show(Strings.权限永久拒绝.toLanguage())
                        // 如果是被永久拒绝就跳转到应用权限系统设置页面
                        XXPermissions.startPermissionActivity(this@LaunchActivity, permissions)
                    } else {
                        ToastUtils.show(Strings.获取权限失败.toLanguage())
                    }
                }
            })
    }

    fun requestLocation() {
        lifecycleScope.launch {
            locationViewModel.getSingleLocation().onSuccess({ location ->
                if (location != null) {
                    // 处理定位成功的情况
                    LogUtils.error("定位成功==> longitude:${location?.longitude},latitude:${location?.latitude}")
                    var latitude = location.latitude
                    var longitude = location.longitude
                    GlobalCache.getFence().filter { TextUtils.equals(it.status ,"1") }?.forEach { fence ->
                        when (fence.type) {
                            "circle" -> {
                                val isInCircle = (CoordinateConverter.calculateLineDistance(DPoint(latitude, longitude), DPoint(fence.latitude, fence.longitude)) <= fence.radius)
                                if (isInCircle){
                                    insideCircleFenceCount++
                                }else {
                                    insideCircleFenceCount = 0
                                }
                                if (TextUtils.equals(fence.trigger, "1")) { //不能出去
                                    if (isInCircle.not() && insideCircleFenceCount >= 10) {
                                        MediaPlayerUtils.getInstance().playAudioByAssets("safe_tip_voice.wav")
                                        EventBus.getDefault().post(ShowLockSceenEvent())
                                        //告警类型 1：带出景区报警 2：带出景区围栏锁机 3：带入禁入区报警 4：带入禁入区围栏报警
                                        viewModel.fenceWarning(hashMapOf("warningType" to 1, "longitude" to longitude, "latitude" to latitude))
                                    } else {
                                        EventBus.getDefault().post(ShowLockSceenEvent(false))
                                    }
                                }
                                if (TextUtils.equals(fence.trigger, "2")) { //不能进入,提示语
                                    if (isInCircle && insideCircleFenceCount>=5) {
                                        EventBus.getDefault().post(ShowSafeTipEvent())
                                        viewModel.fenceWarning(hashMapOf("warningType" to 3, "longitude" to longitude, "latitude" to latitude))
                                    }
                                }
                            }
                            //多边形
                            "polygon" -> {
                                val isInCoordinates = if (fence.coordinates == null) {
                                    false
                                } else {
                                    GeofenceUtils.isPointInPolygon(Coordinate(longitude, latitude), fence.coordinates.map { it.toCoordinates() })
                                }
                                if (isInCoordinates){
                                    insidePolygonFenceCount++
                                }else {
                                    insidePolygonFenceCount = 0
                                }
                                if (TextUtils.equals(fence.trigger, "1")) {//不能出去
                                    if (isInCoordinates.not() && insidePolygonFenceCount >= 10) {
                                        MediaPlayerUtils.getInstance().playAudioByAssets("safe_tip_voice.wav")
                                        EventBus.getDefault().post(ShowLockSceenEvent())
                                        viewModel.fenceWarning(hashMapOf("warningType" to 1, "longitude" to longitude, "latitude" to latitude))
                                    } else {
                                        EventBus.getDefault().post(ShowLockSceenEvent(false))
                                    }
                                }
                                if (TextUtils.equals(fence.trigger, "2")) {//不能进入
                                    if (isInCoordinates && insidePolygonFenceCount>=5) {
                                        EventBus.getDefault().post(ShowSafeTipEvent())
                                        viewModel.fenceWarning(hashMapOf("warningType" to 3, "longitude" to longitude, "latitude" to latitude))
                                    }
                                }
                            }
                        }
                    }
                } else {

                }
            }).onFailure {
                ToastUtils.show(it.message)
            }
        }
    }

    @Subscribe
    fun onMessageEvent(e: VersionUpdateEvent) {
        showProgress()
        viewModel.getVersion()
    }

    @Subscribe
    fun onMessageEvent(e: RecordSosInfoEvent) {
        if (ActivityStackManager.instance.findFirstActivity(LaunchActivity::class.java)?.uniqueIdentifier == this.uniqueIdentifier) {
            lifecycleScope.launch {
                locationViewModel.getSingleLocation().onSuccess({ location ->
                    if (location != null) {
                        viewModel.recordSosInfo(longitude = location.longitude, latitude = location.latitude)
                    }
                })
            }
        }
    }


}